import React, { useState, useRef } from 'react'
import { Table, Space, Button } from 'antd'
import TableModal from './components/TableModal/TableModal'

let newData = [
  {
    key: '1',
    name: 'John Brown',
    age: 9,
    address: 'New York No. 1 Lake Park'
  },
  {
    key: '2',
    name: 'Jim Green',
    age: 18,
    address: 'London No. 1 Lake Park'
  },
  {
    key: '3',
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park'
  }
]

export default function Tables () {
  const modalRef = useRef(null)
  const [record, setRecord] = useState({})
  const [columns, setColumns] = useState([
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: 'Age',
      dataIndex: 'age',
      key: 'age'
    },
    {
      title: 'Address',
      dataIndex: 'address',
      key: 'address'
    },

    {
      title: 'operation',
      key: 'action',
      render: record => (
        <div>
          <Space size='middle' style={{ marginRight: '10px' }}>
            <a onClick={() => deleteItem(record)}>Delete</a>
            <Space size='middle' style={{ marginRight: '10px' }}>
              <a onClick={() => modifyItem(record)}>Modify</a>
            </Space>
          </Space>
        </div>
      )
    }
  ])
  const [data, setData] = useState(newData)
  function deleteItem (record) {
    newData = newData.filter(
      item => item.key !== record.key //过滤删除的数据
    )
    setData(newData)
  }
  function handleAdd () {
    modalRef.current.showModal(true)
  }
  function getValue (value) {
    if (value.cancel) {
      setRecord({})
    }
    console.log(value)
    if (value.key) {
      newData.splice(
        newData.findIndex(i => i.key === value.key),
        1,
        {
          name: value.Name,
          key: value.key,
          age: value.Age,
          address: value.Address
        }
      )
      setRecord({})
      setData([...newData])
    } else if (value.Name) {
      let newValue = {
        key: newData[newData.length - 1].key + '1',
        name: value.Name,
        address: value.Address,
        age: value.Age
      }
      newData.push(newValue)
      setData([...newData]) ///注意
    }
  }

  function modifyItem (record) {
    setRecord(record)
    modalRef.current.showModal(false)
  }
  return (
    <div>
      <Button type='primary' onClick={handleAdd}>
        Add
      </Button>
      <Table columns={columns} dataSource={data} />
      <TableModal
        ref={modalRef}
        getValue={getValue}
        record={record}
      ></TableModal>
    </div>
  )
}
